import React, { useEffect, useRef, useState } from "react";
import { Drawer, Input, Modal, Space, Typography, message } from "antd";

import ProTable, { ProTableRef } from "@/components/TablePro"; // 导入封装的表格组件
import Add from "./add";
import { httpClient } from "@/common/httpClient";
import {
  DeviceInfoFeild,
  PrimaryKey,
  createDeviceInfoFeildField,
} from "./deviceListsFields";
import { Fields, TableAction } from "@/types/public";
import { HearderType } from "@/common/common";
import DataManagementModal from "./devicenodes/deviceNodesLists";
import { useNavigate } from "react-router-dom";
import DeviceTemplate from "./deviceTemplate";

const ProjectLists: React.FC = () => {
  const tableRef = useRef<ProTableRef>(null);
  const [open, setOpen] = useState(false);

  const [updateData, setUpdateData] = useState<DeviceInfoFeild>();
  const [addVisible, setAddVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [projectName, setProjectName] = useState("");
  const [columns, setColumns] = useState<Fields[]>([]); // 正确使用 useState
  const [currentDevice, setCurrentDevice] = useState<DeviceInfoFeild | null>(
    null
  );
  const [isDataModalVisible, setIsDataModalVisible] = useState(false);
  const navigate = useNavigate();
  const DeviceTemplateRef = useRef<any>(null);
  const [modalIsClose, setModalIsClose] = useState(false);
  // 打开数据管理模态框
  const handleOpenDataModal = (record: DeviceInfoFeild) => {
    setCurrentDevice(record);
    setIsDataModalVisible(true);
  };
  // 关闭数据管理模态框
  const handleCloseDataModal = () => {
    setIsDataModalVisible(false);
  };
  // 保存数据管理设置
  const handleSaveDataManagement = (values: any) => {
    message.success("数据管理设置已保存");
    setIsDataModalVisible(false);
  };
  const tableAction: TableAction<DeviceInfoFeild> = {
    detail: (record: DeviceInfoFeild) => {
      setUpdateData(record);
      setOpen(true);
    },
    add: () => {
      setUpdateData(undefined);
      setAddVisible(true);
    },
    edit: (record: DeviceInfoFeild) => {
      setUpdateData(record);
      setAddVisible(true);
    },
    custom: (record: DeviceInfoFeild) => {
      Modal.info({
        title: "设备模板",
        content: (
          <DeviceTemplate modalIsClose={modalIsClose} recoded={record} />
        ),
        closable: true,
        icon: <></>,
        width: "100%",
        style: { top: 0 }, // 修复：使用 style 设置位置
        footer: false,
        onOk: () => {
          // 添加保存逻辑
        },
        afterClose: () => {
          setModalIsClose(true);
        },
      });
    },
    delete: async (rows: DeviceInfoFeild[]) => {
      let res = await httpClient.post(
        "/admin/device/delete",
        { ids: rows.join(",") },
        {
          headers: { "Content-Type": HearderType[0] },
        }
      );
      if (res.data.data) tableRef.current?.refresh();
    },
    migrate: () => {
      setAddVisible(true);
    },
  };
  // 异步加载 columns
  useEffect(() => {
    console.log(123546);
    createDeviceInfoFeildField(tableAction).then((columns: Fields[]) => {
      setColumns(columns);
    });
  }, []);

  const handleSubmit = async (e: any) => {
    let res = await httpClient.post(
      updateData ? "/admin/device/update" : "/admin/device/create",
      updateData ? e : [e],
      updateData
        ? {
            headers: { "Content-Type": HearderType[0] },
          }
        : undefined
    );
    if (res.data.data) tableRef.current?.refresh();
  };

  const handleCloseAdd = () => {
    setAddVisible(false);
  };

  // 模拟API请求
  const fetchProjects = async (params: any) => {
    return await httpClient.get("admin/device/lists", {
      ...params,
    });
  };

  function deleteProject(id: any): void {
    throw new Error("Function not implemented.");
  }

  function migrateProject(id: any): void {
    throw new Error("Function not implemented.");
  }

  return (
    <div id="app-project" className="app-content">
      <Space direction="vertical" size="middle" style={{ display: "flex" }}>
        {/* 项目表格 */}
        <ProTable<DeviceInfoFeild>
          request={fetchProjects}
          tableAction={tableAction}
          columns={columns}
          rowKey={PrimaryKey}
          searchable
          ref={tableRef}
          sticky
          resizable
          debounceWait={800}
        />
      </Space>
      <Add
        initialData={updateData}
        columns={columns}
        visible={addVisible}
        onClose={handleCloseAdd}
        onSubmit={handleSubmit}
      />
      {/* 数据管理模态框 */}
      {/* <DataManagementModal
        visible={isDataModalVisible}
        onCancel={handleCloseDataModal}
        onSave={handleSaveDataManagement}
      /> */}
      <Drawer
        width={"80%"}
        title="详情"
        closable={{ "aria-label": "Close Button" }}
        onClose={() => {
          setOpen(false);
        }}
        open={open} // 修复：使用布尔状态 open，而非函数
      >
        <DataManagementModal
          groupId={updateData?.groupId}
          slaveId={updateData?.slaveAddress}
          deviceId={updateData?.deviceId}
        />
      </Drawer>
    </div>
  );
};

export default ProjectLists;
